<template>
  <el-form :model="editForm" :rules="rules" label-width="135px" ref="editFormRef">
    <!-- 基本信息 -->
    <div class="bg-white my-[10px]">
      <BaseHead>基本信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目名称" prop="name">
              <el-input v-model="editForm.name" placeholder="项目名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目编号">
              {{ editForm.code ? editForm.code : "审核通过后生成" }}</el-form-item
            >
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="chargerName">
              <el-autocomplete
                v-model="editForm.chargerName"
                :fetch-suggestions="queryChargerPerosn"
                clearable
                placeholder="请输入检索关键词"
                value-key="name"
                highlight-first-item
                @select="selectChargerPerosn"
                @blur="chargerPerosnBlur"
                :disabled="verifyRoleType.isKyry()"
              >
                <template #default="{ item }">
                  <span>{{ item.name }}</span>
                  <span class="mx-[10px]">{{ item.account }}</span>
                  <span>{{ item.unitName }}</span>
                </template>
              </el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属单位" prop="unitId">
              <CommonTreeSelect
                placeholder="所属单位"
                v-model="editForm.unitId"
                valueKey="codeColumn"
                labelKey="valueColumn"
                :isFetch="false"
                :dataList="unitList"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人电话" prop="chargerPhone">
              <el-input v-model="editForm.chargerPhone" placeholder="负责人电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目分类" prop="projectTypeCode">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="projectTypeList"
                placeholder="项目分类"
                v-model="editForm.projectTypeCode"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人邮箱" prop="chargerEmail">
              <el-input v-model="editForm.chargerEmail" placeholder="负责人邮箱" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目状态" prop="projectStatusId">
              <CommonRadio
                :isFetch="false"
                :dataList="projectStatusList"
                v-model="editForm.projectStatusId"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="transactor">
              <el-input v-model="editForm.transactor" placeholder="经办人" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人电话" prop="transactorPhone">
              <el-input v-model="editForm.transactorPhone" placeholder="经办人电话" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="立项日期" prop="authorizeDate">
              <el-date-picker
                v-model="editForm.authorizeDate"
                type="date"
                clearable
                placeholder="立项日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="beginDate">
              <el-date-picker
                v-model="editForm.beginDate"
                type="date"
                clearable
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划结项日期" prop="planEndDate">
              <el-date-picker
                v-model="editForm.planEndDate"
                type="date"
                clearable
                value-format="YYYY-MM-DD"
                placeholder="计划结项日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="实际结项日期" prop="actualEndDate">
              <el-date-picker
                v-model="editForm.actualEndDate"
                type="date"
                clearable
                disabled
                value-format="YYYY-MM-DD"
                placeholder="结项日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批准经费" prop="feeAuthorize">
              <el-input
                v-model="editForm.feeAuthorize"
                placeholder="批准经费"
                clearable
                @input="fomateNumber(editForm, 'feeAuthorize', $event)"
                @blur="feeAuthorizeBlur"
              >
                <template #append>万元</template>
              </el-input></el-form-item
            >
          </el-col>
          <el-col :span="12">
            <el-form-item label="成果形式" prop="productMode">
              <el-input v-model="editForm.productMode" placeholder="成果形式" clearable> </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="note">
              <el-input v-model="editForm.note" type="textarea" placeholder="备注" clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
    <!-- 教育部统计信息 -->
    <div class="bg-white">
      <BaseHead>教育部统计信息</BaseHead>
      <div class="p-[10px]">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="统计归属" prop="subjectClassId">
              <CommonRadio
                :isFetch="false"
                :dataList="tjgsList"
                v-model="editForm.subjectClassId"
                valueKey="code"
                @change="tjgschange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="一级学科" prop="subjectId">
              <CommonSelect
                placeholder="一级学科"
                :isFetch="false"
                :dataList="subjectList.value"
                v-model="editForm.subjectId"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="社会经济服务目标" prop="societyTarget">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="jjfwmbList"
                placeholder="社会经济服务目标"
                v-model="editForm.societyTarget"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目来源" prop="projectSourceId">
              <CommonSelect
                placeholder="项目来源"
                :isFetch="false"
                :dataList="projectSourceList.value"
                v-model="editForm.projectSourceId"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="研究类别" prop="researchClassId">
              <CommonSelect
                placeholder="研究类别"
                :isFetch="false"
                :dataList="researchTypeList.value"
                v-model="editForm.researchClassId"
                labelKey="label"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合作单位" prop="cooperateId">
              <CommonSelect
                placeholder="合作单位"
                :isFetch="false"
                :dataList="hzTypeList"
                v-model="editForm.cooperateId"
                valueKey="code"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="国民经济行业" prop="gmjjhy">
              <CommonTreeSelect
                :isFetch="false"
                :dataList="gmjjhyList"
                placeholder="国民经济行业"
                v-model="editForm.gmjjhy"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </div>
  </el-form>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import CommonSelect from "@/views/project/components/CommonSelect.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import useCommonFetch from "@/hooks/useCommonFetch";
import { getPersonList } from "@/api/project/common";
import { baseDetail } from "@/api/project/zx/lxxm";
import { editRecords } from "@/api/project/xj/xmlx";
import { assignObj, verifyRoleType, fomateNumber } from "@/utils/main";
import useUserStore from "@/store/modules/user";
import { emailReg, phoneReg } from "@/utils/validate";
import { ElMessage } from "element-plus";
const userStore = useUserStore();
const unitList = inject("unitList");
const projectTypeList = inject("projectTypeList");
const projectStatusList = inject("projectStatusList");
const tjgsList = inject("tjgsList");
const hzTypeList = inject("hzTypeList");
const jjfwmbList = inject("jjfwmbList");
const gmjjhyList = inject("gmjjhyList");
const isAuditor = inject("isAuditor");
const taskId = inject("taskId");
const checkStatus = inject("checkStatus");
let subjectList = ref([]); //一级学科下拉数据
let researchTypeList = ref([]); //研究类别下拉数据
let projectSourceList = ref([]); //项目来源下拉数据
const editFormRef = ref();
const operateId = ref(null);
const baseInfoData = ref({});
const lastFeeAuthorize = ref(0); //未修改之前的总经费
const editForm = reactive({
  proClass: "xJProject",
  name: "", //项目名称
  code: "", //项目编号
  chargerName: "", //负责人
  chargerCode: "", //负责人ID
  chargerType: "1", //负责人类型 校级默认传教师类型的code:1
  unitId: "", //所属单位
  chargerPhone: "", //负责人电话
  projectTypeCode: "", //项目分类
  chargerEmail: "", //负责人邮箱
  projectStatusId: "", //项目状态
  transactor: "", //经办人
  transactorPhone: "", //经办人电话
  authorizeDate: "", //立项日期
  beginDate: "", //开始日期
  planEndDate: "", //计划结项日期
  actualEndDate: "", //结项日期
  feeAuthorize: "", //批准经费
  productMode: "", //成果形式
  note: "", //备注
  subjectClassId: "", //统计归属
  subjectId: "", //一级学科
  societyTarget: "", //社会经济服务目标
  projectSourceId: "", //项目来源
  researchClassId: "", //研究类别
  cooperateId: "", //合作单位
  gmjjhy: "", //国民经济行业
});
//验证立项日期
const validateAuthorizeDate = (rule, value, callback) => {
  if (editForm.planEndDate) {
    if (new Date(value).getTime() >= new Date(editForm.planEndDate).getTime()) {
      callback(new Error("立项日期必须早于计划结项日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证计划结项日期
const validatePlanEndDate = (rule, value, callback) => {
  if (editForm.authorizeDate) {
    if (new Date(value).getTime() <= new Date(editForm.authorizeDate).getTime()) {
      callback(new Error("计划结项日期必须晚于立项日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = {
  name: [
    {
      required: true,
      message: "项目名称必填",
    },
  ],
  chargerName: [
    {
      required: true,
      message: "负责人必填",
    },
  ],
  unitId: [
    {
      required: true,
      message: "所属单位必填",
    },
  ],
  chargerPhone: [
    {
      required: true,
      message: "负责人电话必填",
    },
    {
      pattern: phoneReg,
      message: "请输入正确的电话号码",
    },
  ],
  chargerEmail: [
    {
      pattern: emailReg,
      message: "请输入正确的邮箱地址",
    },
  ],
  projectTypeCode: [
    {
      required: true,
      message: "项目分类必填",
    },
  ],
  transactorPhone: [
    {
      pattern: phoneReg,
      message: "请输入正确的电话号码",
    },
  ],
  authorizeDate: [
    {
      required: true,
      message: "立项日期必填",
    },
    { validator: validateAuthorizeDate, trigger: "blur" },
  ],
  planEndDate: [
    {
      required: true,
      message: "计划结项日期必填",
    },
    { validator: validatePlanEndDate, trigger: "blur" },
  ],
  feeAuthorize: [
    {
      required: true,
      message: "批准经费必填",
    },
  ],

  subjectClassId: [
    {
      required: true,
      message: "统计归属必填",
    },
  ],
  subjectId: [
    {
      required: true,
      message: "一级学科必填",
    },
  ],
  societyTarget: [
    {
      required: true,
      message: "社会经济服务目标必填",
    },
  ],
  projectSourceId: [
    {
      required: true,
      message: "项目来源必填",
    },
  ],
  researchClassId: [
    {
      required: true,
      message: "研究类别必填",
    },
  ],
  cooperateId: [
    {
      required: true,
      message: "合作单位必填",
    },
  ],
  gmjjhy: [
    {
      required: true,
      message: "国民经济行业必填",
    },
  ],
};
const emit = defineEmits(["save-success", "save-ok"]);
//获取详情
const getBaseInfoData = async () => {
  try {
    const res = await baseDetail(operateId.value);
    baseInfoData.value = res.data;
    lastFeeAuthorize.value = res.data.feeAuthorize;
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = () => {
  operateId.value = null;
  //科研管理员新增默认负责人是自己
  if (verifyRoleType.isKyry()) {
    editForm.chargerName = userStore.nickName;
    editForm.chargerCode = userStore.userRealId;
    editForm.chargerPhone = userStore.phonenumber;
    editForm.chargerEmail = userStore.email;
    editForm.unitId = userStore.deptId;
  }
};
// 编辑
const edit = async (id) => {
  operateId.value = id;
  nextTick(async () => {
    await getBaseInfoData();
    //表单表格赋值
    assignObj(editForm, baseInfoData.value);
  });
};
const save = async (submitType) => {
  try {
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let params = {
          ...editForm,
          submitType,
          isAuditor: isAuditor.value,
          taskId: taskId.value,
          checkstatus: checkStatus.value,
        };
        if (operateId.value) {
          params.id = operateId.value;
        }
        const res = await editRecords(params);
        if (res.code === 200) {
          emit("save-success", res.data);
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    emit("save-ok");
  }
};
defineExpose({ add, edit, save });
//批准经费输入框失去焦点
const feeAuthorizeBlur = () => {
  if (operateId.value && lastFeeAuthorize.value != editForm.feeAuthorize) {
    ElMessage({
      message: `批准经费已经更改，请修改预算明细！`,
      type: "warning",
    });
  }
};
//根据姓名查询负责人
const queryChargerPerosn = async (queryString, cb) => {
  if (queryString.trim() == "") {
    return;
  }
  editForm.chargerCode = "";
  const params = {
    name: queryString,
  };
  try {
    const res = await getPersonList(params);
    cb(res.data);
  } catch (error) {
    console.log(error);
  }
};
//选择负责人
const selectChargerPerosn = (val) => {
  editForm.chargerCode = val.id;
  editForm.chargerEmail = val.email;
  editForm.chargerPhone = val.mobile;
  editForm.unitId = val.unitId;
};
//清空负责人字段的值
const resetChargerPerosn = () => {
  editForm.chargerCode = "";
  editForm.chargerName = "";
  editForm.chargerEmail = "";
  editForm.chargerPhone = "";
  editForm.unitId = "";
};
//选择负责人框失去焦点
const chargerPerosnBlur = () => {
  if (!editForm.chargerCode) {
    resetChargerPerosn();
  }
};
//监听统计归属的值改变
watch(
  () => editForm.subjectClassId,
  (newVal) => {
    subjectList.value = useCommonFetch("一级学科", newVal);
    researchTypeList.value = useCommonFetch("研究类别", newVal);
    projectSourceList.value = useCommonFetch("项目来源", newVal);
  }
);
//手动改变统计归属的值 清空一级学科、项目来源、研究类别的值
const tjgschange = () => {
  editForm.subjectId = "";
  editForm.projectSourceId = "";
  editForm.researchClassId = "";
};
</script>

<style scoped lang="scss"></style>
